package com.yonyou.brigade.third_parties.smectrip.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.smectrip.dao.CtripSmeUserMapper;
import com.yonyou.brigade.third_parties.smectrip.model.CtripSmeUser;
import com.yonyou.brigade.third_parties.smectrip.service.ISmeCtripPublicService;
import com.yonyou.brigade.third_parties.smectrip.service.ISmeCtripUserService;
import com.yonyou.brigade.util.operateutil.CompareUtils;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/25.
 */
@Service
public class SmeCtripUserServiceImpl extends ServiceImpl<CtripSmeUserMapper, CtripSmeUser> implements ISmeCtripUserService {

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    private CtripSmeUserMapper ctripSmeUserMapper;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Autowired
    @Qualifier("smeCtripPublicServiceImpl")
    private ISmeCtripPublicService smeCtripPublicService;

    @Autowired
    private PropUtil propUtil;

    private String CompareProperties="dept1,dept2,email,employeeId,mobile,name,valid," +
            "hasBookingForOther,birthday,firstName,lastName,cost1,gender,nationality,superiorEid,custId";

    private static final Logger logger = LoggerFactory.getLogger(SmeCtripUserServiceImpl.class);


    @Override
    public void getLoginInfo(String tenant, String org, String phone, String initPage, String source, HttpServletResponse response,BriChannel briChannel) throws IOException {
        String config = briChannel.getConfig();
        Wrapper<CtripSmeUser> ctripSmeUserWrapper = new EntityWrapper<>();
        ctripSmeUserWrapper.where("tenant={0}", tenant);
        ctripSmeUserWrapper.and("mobile={0}", phone);
        List<CtripSmeUser> ctripSmeUsers = ctripSmeUserMapper.selectList(ctripSmeUserWrapper);
        UcUserDto ucUserDtoByPhone = iUserCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
        if (ucUserDtoByPhone == null){
            throw new BusinessException("用户中心中该用户不存在 ！ phone" + phone);
        }
        CtripSmeUser ctripSmeUser = getCtripSMEUser(ucUserDtoByPhone, tenant);
        if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
            if(ctripSmeUsers != null && ctripSmeUsers.size() > 0) {
                Map<String,String> compareMap = new HashMap<>();
                String[] compareFields = CompareProperties.split(",");
                if(compareFields != null && compareFields.length > 0) {
                    for(int i = 0; i < compareFields.length; i++) {
                        compareMap.put(compareFields[i],"");//此处只需要key值
                    }
                }
                if("pc".equals(source)){
                    JSONArray memberInfoModelArray = new JSONArray();
                    JSONObject memberInfoModel = new JSONObject();
                    memberInfoModel.put("EmployeeID", ctripSmeUser.getEmployeeId());
                    memberInfoModel.put("Name", ctripSmeUser.getName());
                    memberInfoModel.put("Mobile", ctripSmeUser.getMobile());
                    memberInfoModel.put("IsUsed", ctripSmeUser.getValid());
                    memberInfoModel.put("IsManager", true);
                    memberInfoModelArray.add(memberInfoModel);
                    smeCtripPublicService.syncCtripSmeUsers(tenant, memberInfoModelArray, briChannel.getConfig());
                    ctripSmeUser.setaManager(true);
                    ctripSmeUser.setId(ctripSmeUsers.get(0).getId());
                    ctripSmeUserMapper.updateById(ctripSmeUser);
                }
                Map<String,Object> compareResult= CompareUtils.getModifyContent(ctripSmeUsers.get(0),ctripSmeUser,compareMap);
                if(compareResult!=null&&compareResult.size()>0) {
                    logger.info("sme存在不同的字段，开始进行更新操作" + ctripSmeUser.getMobile());
                    //更新已经同步过的用户信息
                    JSONArray memberInfoModelArray = new JSONArray();
                    JSONObject memberInfoModel = new JSONObject();
                    memberInfoModel.put("EmployeeID", ctripSmeUser.getEmployeeId());
                    memberInfoModel.put("Name", ctripSmeUser.getName());
                    memberInfoModel.put("Mobile", ctripSmeUser.getMobile());
                    memberInfoModel.put("IsUsed", ctripSmeUser.getValid());
                    memberInfoModelArray.add(memberInfoModel);
                    boolean flag = smeCtripPublicService.syncCtripSmeUsers(tenant, memberInfoModelArray, config);
                    if (flag) {
                        ctripSmeUser.setId(ctripSmeUsers.get(0).getId());
                        ctripSmeUserMapper.updateById(ctripSmeUser);
                    }
                }
                //do nothing
            }else {
                JSONArray memberInfoModelArray = new JSONArray();
                JSONObject memberInfoModel = new JSONObject();
                memberInfoModel.put("EmployeeID",ctripSmeUser.getEmployeeId());
                memberInfoModel.put("Name",ctripSmeUser.getName());
                memberInfoModel.put("Mobile",ctripSmeUser.getMobile());
                memberInfoModel.put("IsUsed",ctripSmeUser.getValid());
                if("pc".equals(source)) {
                    memberInfoModel.put("IsManager", true);
                    ctripSmeUser.setaManager(true);
                }
                memberInfoModelArray.add(memberInfoModel);
                boolean flag = smeCtripPublicService.syncCtripSmeUsers(tenant, memberInfoModelArray, config);
                if (flag){
                    ctripSmeUserMapper.insert(ctripSmeUser);
                }
            }
        }
        ctripSmeUsers = this.baseMapper.selectList(ctripSmeUserWrapper);
        if(ctripSmeUsers != null && ctripSmeUsers.size() > 0) {
            ctripSmeUser = ctripSmeUsers.get(0);
            smeCtripPublicService.ssoLogin(ctripSmeUser, response, config, initPage, source);
        }

    }



    @Override
    public void syncAllUsersToCtripSME(String tenant, String config, String phone) {
        List<UcUserDto> ucUsersByTenantId = iUserCenterService.getUcUsersByTenantId(tenant);
        if (!CollectionUtils.isEmpty(ucUsersByTenantId)) {
            ArrayList<CtripSmeUser> usersNeedUpdate = new ArrayList<>();
            ArrayList<CtripSmeUser> usersNeedInsert = new ArrayList<>();
            for (int i = 0; i < ucUsersByTenantId.size(); i++) {
                UcUserDto ucUserDto = ucUsersByTenantId.get(i);
                CtripSmeUser ctripSMEUser = getCtripSMEUser(ucUserDto, tenant);

                if (!StringUtils.isEmpty(phone) && phone.equals(ctripSMEUser.getMobile())) {
                    ctripSMEUser.setaManager(true);
                }
                Wrapper<CtripSmeUser> ctripSmeUserWrapper = new EntityWrapper<>();
                ctripSmeUserWrapper.where("tenant={0}", tenant);
                ctripSmeUserWrapper.and("mobile={0}", ctripSMEUser.getMobile());
                List<CtripSmeUser> ctripSmeUsers = ctripSmeUserMapper.selectList(ctripSmeUserWrapper);
                if (!CollectionUtils.isEmpty(ctripSmeUsers)) {
                    Map<String,String> compareMap = new HashMap<>();
                    String[] compareFields = CompareProperties.split(",");
                    if(compareFields != null && compareFields.length > 0) {
                        for(int j = 0; j < compareFields.length; j++) {
                            compareMap.put(compareFields[j],"");//此处只需要key值
                        }
                    }
                    Map<String,Object> compareResult = CompareUtils.getModifyContent(ctripSmeUsers.get(0), ctripSMEUser, compareMap);
                    if(!CollectionUtils.isEmpty(compareResult)) {
                        //需要更新的已同步的人员
                        ctripSMEUser.setId(ctripSmeUsers.get(0).getId());
                        usersNeedUpdate.add(ctripSMEUser);
                    }
                    //对于无需更新的人员不作处理
                } else {
                    //需要新增并同步人员(每天每个租户最多500人)
                    if (usersNeedInsert.size() <= 500) {
                        usersNeedInsert.add(ctripSMEUser);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(usersNeedInsert)) {
                syncUsersToCtripSME(usersNeedInsert, tenant, config, "insert");
            }
            if (!CollectionUtils.isEmpty(usersNeedUpdate)) {
                syncUsersToCtripSME(usersNeedUpdate, tenant, config, "update");
            }
        }
    }


    private void syncUsersToCtripSME(ArrayList<CtripSmeUser> usersNeedDealWith, String tenant, String config, String dealType) {
        //一次不能同步超过30个数据，completeUcUserDtosByUserids按照30个分组
        for (int i = 0; i < usersNeedDealWith.size(); i += 30) {
            List<CtripSmeUser> syncResultList = new ArrayList<>();
            List<CtripSmeUser> smallList = new ArrayList<>();
            for (int j = 0; j < 30 && i + j < usersNeedDealWith.size(); j++) {
                smallList.add(usersNeedDealWith.get(i + j));
            }
            JSONArray memberInfoModelArray = new JSONArray();
            for (CtripSmeUser ctripSmeUser : smallList) {
                JSONObject memberInfoModel = new JSONObject();
                memberInfoModel.put("EmployeeID", ctripSmeUser.getEmployeeId());
                memberInfoModel.put("Name", ctripSmeUser.getName());
                memberInfoModel.put("Mobile", ctripSmeUser.getMobile());
                memberInfoModel.put("IsUsed", ctripSmeUser.getValid());
                memberInfoModel.put("IsManager", ctripSmeUser.getaManager());
                //需要给携程商旅通同步的人员信息
                memberInfoModelArray.add(memberInfoModel);
                //本地CtripSmeUser
                syncResultList.add(ctripSmeUser);
            }
            //同步给携程商旅通并存到本地
            boolean flag = smeCtripPublicService.syncCtripSmeUsers(tenant, memberInfoModelArray, config);
            if (flag) {
                switch (dealType) {
                    case "insert":
                        this.insertBatch(syncResultList);
                        break;
                    case "update":
                        this.updateBatchById(syncResultList);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 用户中心的用户转化为写携程商旅通用户
     * @param ucUserDto
     * @return
     */
    private CtripSmeUser getCtripSMEUser(UcUserDto ucUserDto,String tenant) {
        CtripSmeUser ctripSmeUser = new CtripSmeUser();
        ctripSmeUser.setTenant(tenant);
        ctripSmeUser.setOrg(ucUserDto.getOrgPk());
        ctripSmeUser.setUserId(ucUserDto.getUserId());
        ctripSmeUser.setBirthday(ucUserDto.getBirthday());
        ctripSmeUser.setDept1(ucUserDto.getOrgName());
        ctripSmeUser.setDept2(ucUserDto.getDeptName());
        ctripSmeUser.setEmployeeId(ucUserDto.getPersonCode());
        ctripSmeUser.setEmail(ucUserDto.getEmail());
        ctripSmeUser.setMobile(ucUserDto.getPhone());
        ctripSmeUser.setName(ucUserDto.getUserName());
        ctripSmeUser.setGender("0");
        ctripSmeUser.setHasBookingForOther(0);
        ctripSmeUser.setValid(ucUserDto.getDr() == 0 ? true : false);

        return ctripSmeUser;

    }

}